<?php
include_once('./db.conf');
session_start();
$loggedIn=false;
// Connects to your Database 
$connection=mysqli_connect(DBHOST, DBUSER, DBPASS,DBDBNAME); 

if(isset($_COOKIE['AdminCookie'])){
	$_SESSION['adminName']=$_COOKIE['AdminCookie'];
	$loggedIn=true;
	header("Location: indexAdmin.php");
}
//if the login form is submitted

if (!$loggedIn && isset($_POST['submit'])) { // if form has been submitted


// makes sure they filled it in

	if(!$_POST['pass'] | !$_POST['name']) {
		die('You did not fill in a required field.');
	}

	// checks it against the database
	$query = "call getAdminPass('$_POST[name]')";
	if(!$check = mysqli_query($connection,$query))
		echo mysqli_error($connection);
	else{
		$row= mysqli_fetch_assoc($check);
		if($row['passwd']==$_POST['pass']){
			$_SESSION['adminName']=$row['name'];
			$name=$row['name'];
			$hour=time()+300;//expires 5 minutes later
			setcookie('AdminCookie',$name,$hour);
			header("Location: indexAdmin.php");
		}
		else
			echo "Wrong Password or Name";
	}
}
 else {	

// if they are not logged in
?>

<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login For Admin</h1></td></tr>
<tr><td>Name:</td><td>
<input type="text" name="name" maxlength="40">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="pass" maxlength="50">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
<?php
}
mysqli_close($connection);
?> 
